﻿using HenuAlbum.ControllerModels;
using HenuAlbum.DbContext;
using HenuAlbum.Identity;
using HenuAlbum.Models;
using HenuAlbum.ResponseModels;
using HenuAlbum.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HenuAlbum.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SchoolAlbumController : ControllerBase
    {
        private readonly UserManager<User> _userManager;
        private readonly AppDbContext _appDbContext;

        public SchoolAlbumController(UserManager<User> userManager, AppDbContext appDbContext)
        {
            _userManager = userManager;
            _appDbContext = appDbContext;
        }

        [HttpPost("Add")]
        [Authorize(Roles = "管理员")]
        public async Task<IActionResult> AddAlbum(AddPersonalAlbumParams param)
        {
            //获取管理员身份信息
            var user = await _userManager.GetUserAsync(this.User);
            //创建相册
            SchoolAlbum schoolAlbum = new SchoolAlbum()
            {
                Title = param.Title,
                Description = param.Description,
                CreateTime = DateTime.Now,
                IsPublic = param.IsPublic,
                Creator = user,
            };
            await _appDbContext.SchoolAlbums.AddAsync(schoolAlbum);
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse()
            {
                Data = new
                {
                    schoolAlbum.Id,
                    schoolAlbum.Title,
                    schoolAlbum.Description,
                    schoolAlbum.CreateTime,
                    schoolAlbum.IsPublic
                }
            });
        }

        [HttpGet]
        public async Task<IActionResult> GetAll(int limit = 20, int page = 1)
        {
            var data = await _appDbContext.SchoolAlbums.Include(x=>x.Resources).AsNoTracking().ToListAsync();

            if (!User.IsInRole("管理员"))
            {
                data.RemoveAll(x => !x.IsPublic);
            }
            if (null == data)
            {
                return BadRequest(new IncorrectError("权限不够或相册不存在"));
            }

            Tools.ResolveLimitAndPage(ref limit, ref page, 20, 100);
            var result = data.OrderBy(y=>y.Id).Skip(limit*(page-1)).Take(limit).Select(x => new
            {
                x.Id,
                x.Title,
                x.Description,
                CoverId = x.Resources.FirstOrDefault()?.Id,
                x.IsPublic,
                LikeCount = _appDbContext.UserLikeAlbum.Count(y => y.AlbumId == x.Id),
                DownloadCount = x.Resources.Select(f => f.DownloadCount).FirstOrDefault()
            });
            return Ok(new OkResponse() { Data = result });
        }

        [HttpPost("{albumid:int}/Delete")]
        [Authorize(Roles = "管理员")]
        public async Task<IActionResult> Delete(int albumid)
        {
            var album = await _appDbContext.SchoolAlbums.Where(x => x.Id == albumid).FirstOrDefaultAsync();
            if (null == album)
            {
                return BadRequest(new NotExistsError("相册不存在"));
            }
            _appDbContext.SchoolAlbums.Remove(album);
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse());
        }


        [HttpPost("{albumid:int}/Update")]
        [Authorize(Roles = "管理员")]
        public async Task<IActionResult> Update(int albumid, AddPersonalAlbumParams param)
        {
            var album = await _appDbContext.SchoolAlbums.Where(x => x.Id == albumid).FirstOrDefaultAsync();
            if (null == album) return BadRequest(new IncorrectError("相册不存在"));

            album.IsPublic = param.IsPublic;
            album.Title = param.Title;
            album.Description = param.Description;
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse());
        }

        [HttpGet("{albumid:int}/Detail")]
        public async Task<IActionResult> GetDetail(int albumid)
        {
            var data = await _appDbContext.SchoolAlbums.Include(t=>t.Resources).AsNoTracking().Where(x => x.Id == albumid).FirstOrDefaultAsync();
            if (null == data) return BadRequest(new NotExistsError("资源不存在"));
            if (User.IsInRole("管理员") || data.IsPublic)
            {
                return Ok(new OkResponse()
                {
                    Data = new
                    {
                        data.Id,
                        data.Title,
                        data.Description,
                        data.IsPublic,
                        data.CreatorId,
                        data.CreateTime,
                         LikeCount = _appDbContext.UserLikeAlbum.Count(y => y.AlbumId == data.Id),
                        DownloadCount = data.Resources.Select(f => f.DownloadCount).FirstOrDefault()

                    }
                });

            }
            else
            {
                return BadRequest("权限不允许");
            }
        }

    }
}
